package com.carr.controller;

import com.carr.api.dto.ActProcessDefDto;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author yulin.chen
 * @classname InstanceController
 * @description TODO
 * @date 2020/9/24 13:39
 */
@RestController
@RequestMapping("/process/def")
public class ProcessDefController {

    private final RepositoryService repositoryService;

    public ProcessDefController(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }


    @GetMapping("/list")
    public Object getProcessInstanceList(@RequestParam(value = "name")String name,@RequestParam(value = "resourceName")String resourceName) {
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
        if (StringUtils.isNotEmpty(name)) {
            query.processDefinitionNameLike("%"+name+"%");
        }
        if (StringUtils.isNotEmpty(resourceName)) {
            query.processDefinitionResourceNameLike("%"+resourceName+"%");
        }
        List<ProcessDefinition> queryList = query
                .orderByProcessDefinitionVersion().asc()//按照版本的升序排列
                .orderByProcessDefinitionName().desc()//按照流程定义的名称降序排列
                .list();
        List<ActProcessDefDto> list = new ArrayList<>();
        queryList.forEach(item->{
            ActProcessDefDto defDto = new ActProcessDefDto();
            BeanUtils.copyProperties(item,defDto);
            list.add(defDto);
        });

        HashMap<String, Object> map = new HashMap<>();
        map.put("recordsTotal", list.size());
        map.put("recordsFiltered", list.size());
        map.put("data", list);
        return map;
    }
}
